﻿#include "maker.h"
#include "ui_maker.h"

Maker::Maker(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Maker)
{
    ui->setupUi(this);
}

Maker::~Maker()
{
    delete ui;
}

void Maker::on_btn_pickDir_clicked()
{
    targetDir=QFileDialog::getExistingDirectory(this,QStringLiteral("选择目标文件夹"));
    if(targetDir.isEmpty())
        return;

    QUrl url=QUrl::fromLocalFile(targetDir);
    ui->path->setText(QString(LINKS).arg(url.url()).arg(targetDir));
}

void Maker::on_btn_pick_clicked()
{
    QString fileName=QFileDialog::getOpenFileName(this,QStringLiteral("选择文本文件"),
                                                  QString(),"Text (*.txt)");
    QFile file(fileName);
    if(file.open(QFile::ReadOnly | QFile::Text))
    {
        QTextStream stream(&file);
        ui->content->setPlainText(stream.readAll());
    }
}

void Maker::on_btn_process_clicked()
{
    if(targetDir.isEmpty())
    {
        QMessageBox::warning(this,QStringLiteral("无效操作"),
                             QStringLiteral("未设置有效文件夹"));
        return;
    }

    QString content=ui->content->toPlainText();
    if(content.isEmpty())
        return;

    QStringList lines{};
    QTextStream stream(&content,QIODevice::ReadOnly);
    QString line{};
    while (stream.readLineInto(&line)) {
        if(line.isEmpty())
            continue;

        if(!lines.contains(line))
            lines.append(line);
    }

    if(lines.isEmpty())
        return;

    do_makeDir(lines);
}

void Maker::do_makeDir(const QStringList &items)
{
    QDir dir=QDir::current();
    dir.cd(targetDir);
    foreach (QString item, items) {
        dir.mkdir(item);
    }
    ui->status->setText(QStringLiteral("操作完成"));
}

void Maker::on_btn_clean_clicked()
{
    ui->content->clear();
    ui->status->clear();
}
